import Ember from 'ember';
import {
  calculateSelected
}
from '../../../utils/mlist-util';

export default Ember.Controller.extend({
  queryParams: ['page', 'size', 'q'],
  indexController: Ember.inject.controller('treenodes.index'),
  treeModel: Ember.computed.reads('indexController.model'),
  size: 10,
  page: 0,
  qv: "",
  qvChanged: Ember.observer('qv', function() {
    this.set('q', this.get('qv'));
  }),
  menus: [{
    name: 'create',
    action: "create",
    label: "新增",
    showWhen: "always"
  }, {
    name: 'delete',
    action: "delete",
    label: "删除",
    showWhen: "some"
  }, {
    name: 'edit',
    action: "edit",
    label: "编辑",
    showWhen: "one"
  }],
  selectedState: Ember.computed('children.@each.isSelected', function() {
    return calculateSelected(this.get('children'), true);
  }),
  meta: Ember.computed('children', function() {
    var children = this.get('children');
    return {
      total: children.length,
      size: this.get('size')
    };
  }),
  children: Ember.computed('page', 'size', 'q','model',function() {
    var treeModel = this.get('treeModel'),
      model = this.get('model'),
      treeJson = treeModel.get('treeJson');
    if (!parent) {
      return treeJson.root.c;
    } else {
      return model.get('c');
    }
  }),
  actions: {
    menuClicked(mname) {
      var treeModel = this.get('treeModel'),
          model = this.get('model');

      if (mname === 'create') {
        this.transitionToRoute("treenodes.index.new", treeModel, model);
      } else if(mname === 'edit') {
        var c = model.get('c'),
            selected = c.find((it) => {
              return it.get('isSelected');
            });
        if (selected) { //编辑选定的节点。
          this.transitionToRoute("treenodes.index.edit", treeModel, selected);
        }
      }
    },
    breadNodeClicked(node) {
      this.transitionToRoute('treenodes.index.children', this.get('treeModel'), node);
    }
  }
});
